package com.codefalse.mybatis.generator.listener;

import javafx.event.EventHandler;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.MouseEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Pattern;

/**
 * @author songxiangfeng
 * Created At 2019-12-14 15:07
 */
@Slf4j
public class DatabaseClickListener implements EventHandler<MouseEvent> {

    private DatabaseChangeListener listener;

    public DatabaseClickListener(DatabaseChangeListener listener) {
        this.listener = listener;
    }

    @Override
    public void handle(MouseEvent event) {
        TreeView treeView = (TreeView) event.getSource();
        ContextMenu contextMenu = treeView.getContextMenu();
        TreeItem treeItem = (TreeItem) treeView.getSelectionModel().getSelectedItem();
        if (treeItem == null) {
            return;
        }
        //判断是否点击数据库
        TreeItem parentItem = treeItem.getParent();
        Pattern pattern = Pattern.compile("^(schema)\\([0-9]*\\)");
        if (pattern.matcher(parentItem.getValue().toString()).matches()) {
            TreeItem configTreeItem = parentItem.getParent();
            String configName = configTreeItem.getValue().toString();
            String database = treeItem.getValue().toString();
            log.debug("当前配置名称：{}, 数据库为：{}", configName, database);
            switch (event.getButton()) {
                case PRIMARY:
                    listener.currentDatabase(configName, database);
                    break;
                case SECONDARY:
                    MenuItem menuItem = contextMenu.getItems().get(0);
                    menuItem.setVisible(true);
                    break;
            }
        }
    }
}
